import { ApiCall } from "tsrpc";
import { ReqAttack, ResAttack } from "../../../shared/master/word/PtlAttack";
import { player } from "../../../model/fight/body/player";
import { template } from "../../../shared/master/MsgAction";
import { pet } from "../../../model/fight/body/pet";

export default async function (call: ApiCall<ReqAttack, ResAttack>) {
    call.succ({})
    let user = call.req._player as player;
    if(user.is_die()){
        await user.callApi('word/ResLife',{})
        if(user.is_die()){
            user.sendMsg(template.default,'你已死亡请先[复活].')
            return;
        }
    }
    let _cell = user.getPosition();
    let tagBody;
    switch (call.req.type) {
        case 0:
            if (call.req.idx) {
                tagBody = _cell.get_Body_index(call.req.idx - 1);
                if (!tagBody) {
                    user.sendMsg(template.default, `没有找到ID为[${call.req.idx}]的敌人`)
                    return;
                }

            } else {
                // 随机攻击
                tagBody = _cell.get_Body_weak()
                if (!tagBody) {
                    user.sendMsg(template.default, `当前位置已经没有可攻击的怪物了`)
                    return;
                }
            }
            break;
        case 1:
            // 攻击玩家
            if (call.req.idx) {
                tagBody = _cell.get_Body_index(call.req.idx - 1);
                if (!tagBody) {
                    user.sendMsg(template.default, `没有找到ID为[${call.req.idx}]的玩家`)
                    return;
                }
                if (!(tagBody instanceof player)) {
                    user.sendMsg(template.default, `ID[${call.req.idx}]的单位不是玩家.`)
                    return;
                }
            } else {
                user.sendMsg(template.default, `你需要指定攻击的玩家ID才能攻击玩家.`)
                return;
            }
            break;
        case 2:
            let arry = _cell.get_Body_idle();
            if (arry.length <= 1) {
                user.sendMsg(template.default, `当前位置没有闲置中的单位.`)
                return;
            }
            for (let index = 0; index < arry.length; index++) {
                const element = arry[index];
                if (element.uuid == user.uuid) {
                    continue;
                }
                _cell.attack(user.uuid, element.uuid);
            }
            user.sendMsg(template.default, `${user.nickName}向${arry.length - 1}个单位发起战斗.`)
            return;
        default:
            break;
    }

    if (tagBody.is_die()) {
        user.sendMsg(template.default, `${tagBody.nickName}单位已死亡.`)
        return;
    }
    if (tagBody instanceof pet) {
        user.sendMsg(template.default, `${tagBody.nickName}为他人放生宠物,暂无法攻击.`)
        return;
    }
    _cell.attack(user.uuid, tagBody.uuid);

}